package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

var count int64
var wg sync.WaitGroup

func incrementor() {
	for i := 0; i < 10; i++ {
		atomic.AddInt64(&count, 1)
	}
	wg.Done()
}

func multiIncrementor(n int) int {
	rs := make(chan int)
	done := make(chan bool)
	var wg sync.WaitGroup
	wg.Add(n)

	for i := 0; i < n; i++ {
		go func() {
			t := 0
			for j := 0; j < 10; j++ {
				t += j
			}
			rs <- t
			done <- true
		}()
	}

	total := 0
	go func(n *int) {
		for r := range rs {
			*n += r
			wg.Done()
		}
	}(&total)

	go func() {
		for i := 0; i < n; i++ {
			<-done
		}
		close(rs)
	}()

	wg.Wait()
	fmt.Println("total :", total)
	return total
}

func main() {
	wg.Add(2)
	go incrementor()
	go incrementor()
	wg.Wait()
	fmt.Println("final count is ", count)

	fmt.Println("==============")
	fmt.Println("==", multiIncrementor(10))
}
